<template>
  <div class="box">
    <div class="left">
      <div class="menus">
        <a-menu mode="inline" @click="handleClick" :selectedKeys="[state.work]">
          <template v-for="(work, i) in works">
            <a-sub-menu v-if="work.children" :key="i">
              <template #title>{{ work.label }}</template>
              <a-menu-item v-for="child in work.children" :key="child.value">{{
                child.label
              }}</a-menu-item>
            </a-sub-menu>
            <a-menu-item v-else :key="work.value">{{ work.label }}</a-menu-item>
          </template>
        </a-menu>
      </div>
      <div
        :class="{ extra: true, active: state.work === '-1' }"
        @click="handleClick({ key: '-1' })"
      >
        <thunderbolt-outlined /> 压缩空气电气转换
      </div>
    </div>
    <div class="right">
      <p :style="{ textAlign: 'right', marginBottom: '10px' }">
        <a-button type="link" @click="downloadTemplate">
          <template #icon>
            <download-outlined />
          </template>
          下载模板
        </a-button>
                <a-upload
          :showUploadList="false"
          accept=".xls,.xlsx"
          :customRequest="
            ({ file }) => {
              uploadExcel(file);
            }
          "
          :disabled="disabled"
        >
          <a-button type="link" :disabled="disabled">
            <upload-outlined></upload-outlined>
            上传
          </a-button>
        </a-upload>
        <a-button @click="action('add')" type="primary" link
          ><template #icon>
            <PlusOutlined />
          </template>
          添加</a-button
        >
      </p>
      <a-table
        :dataSource="state.data"
        :columns="state.columns"
        bordered
        :scroll="{ x: 1200 }"
        size="small"
        rowKey="id"
        :pagination="state.pager"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space :size="10" spacer="|">
              <DeleteBtn
                title="确认删除?"
                label="删除"
                @onDelete="action('remove', record)"
              />
              <a-button type="link" @click="action('edit', record)" link
                ><template #icon>
                  <EditOutlined />
                </template>
                编辑</a-button
              >
            </a-space>
          </template>
        </template>
        <template v-if="state.innerColumns" #expandedRowRender="{ record }">
          <p :style="{ textAlign: 'right', marginBottom: '4px' }">
            <a-button
              @click="innerAction('add', { pid: record.id })"
              type="text"
              ><template #icon>
                <PlusOutlined />
              </template>
              添加</a-button
            >
          </p>
          <a-table
            :columns="state.innerColumns"
            :data-source="record.inner"
            :pagination="false"
            rowKey="id"
            bordered
            size="small"
          >
            <template #bodyCell="{ column: innerColumn, record: innerRecord }">
              <template v-if="innerColumn.key === 'action'">
                <a-space :size="10" spacer="|">
                  <DeleteBtn
                    title="确认删除?"
                    type="text"
                    @onDelete="innerAction('remove', innerRecord)"
                  />
                  <a-button
                    type="text"
                    @click="
                      innerAction('edit', { ...innerRecord, pid: record.id })
                    "
                    ><template #icon> <EditOutlined /> </template
                  ></a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </template>
      </a-table>
    </div>
  </div>
  <FormModal
    v-if="state.formConfig"
    :formConfig="state.formConfig"
    ref="dialogRef"
    @submit="submit"
  />
  <FormModal
    v-if="state.innerFormConfig"
    :formConfig="state.innerFormConfig"
    ref="dialogInnerRef"
    @submit="innerSubmit"
  />
</template>
<script setup>
import {
  onBeforeMount,
  getCurrentInstance,
  reactive,
  ref,
  computed,
} from "vue";
import {
  works,
  workColumns,
  showWorkLabel,
  innerColumns,
  workFormItems,
  innerFormItems,
  airToPowerColumns,
  airToPowerFormItems,
} from "@/utils/workflow";
import DeleteBtn from "@/components/DeleteBtn.vue";
import FormModal from "@/components/FormModal.vue";
import _ from "lodash";
import dayjs from "dayjs";

const { proxy } = getCurrentInstance();

const state = reactive({
  work: "0",
  ships: [],
  columns: [],
  data: [],
  pager: {
    current: 1,
    pageSize: 12,
    total: 0,
    showSizeChanger: false,
    size: "normal",
  },
  formConfig: null,
  innerColumns: null,
  innerFormConfig: null,
});
const dialogRef = ref();
const dialogInnerRef = ref();

const apis = {
  "-1": "/calibration_air_power",
  0: "/calibration_ship_cut",
  1: "/calibration_ship_old",
  2: "/calibration_ship_weld",
  "3-0": "/calibration_machine_pipe_falan",
  "3-1": "/calibration_machine_pipe_wantou",
  "4-0": "/calibration_paint_house",
  "4-1": "/calibration_paint_ship",
  "5-0": "/calibration_house_sand",
  "5-1": "/calibration_ship_sand",
  "6-0": "/calibration_water_clean_point",
  "6-1": "/calibration_water_clean",
  "6-2": "/calibration_water_rust_clean",
  "6-3": "/calibration_water_clean_rust_ship",
};

const templateTypes = {
  "-1": 7,      // 压缩空气电气转换
  "0": 1,       // 船体下料
  "1": 2,       // 船体割旧
  "2": 3,       // 船体焊接
  "3-0": 4,     // 法兰管子焊接
  "3-1": 5,     // 弯头管子焊接
  "4-0": 6,     // 喷漆房分段喷漆
  "4-1": 7,     // 舱室及船壳喷漆
  "5-0": 8,     // 打砂房分段打砂
  "5-1": 9,     // 舱室打砂
  "6-0": 10,    // 超水清洁点打
  "6-1": 11,    // 超水清洁
  "6-2": 12,    // 超水除锈
  "6-3": 13,    // 舱盖超水除锈
};

const uploadExcel = async (file) => {

  const url = apis[state.work];
  if (!url) {
    proxy.$message.error("未知的工作流程，无法上传文件");
    return;
  }
  // 1. 文件校验（可选）
  const isExcel =
    file.type === "application/vnd.ms-excel" ||
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

  if (!isExcel) {
    proxy.$message.error("只能上传 Excel 文件（.xls 或 .xlsx）!");
    return false;
  }

  // 限制文件大小（例如 10MB）
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    proxy.$message.error("文件大小不能超过 10MB！");
    return false;
  }

  const formData = new FormData();
  formData.append("file", file);
 
    // 3. 调用上传接口
    const { success, msg } = await proxy.$axios.post(
      "/excel/import/"+url, // 后端上传接口路径
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );

    // 4. 处理响应
    if (success) {
      proxy.$message.success("文件上传成功！");
      // 上传成功后刷新数据
      getOrders(1);
    } else {
      proxy.$message.error(msg || "上传失败，请检查文件内容");
    }

};

const downloadTemplate = () => {

  const work = state.work;
  
  // 1. 获取对应的模板 type
  const type = templateTypes[work];
  console.log('type',type)
// 1. 获取当前 work 对应的 API 接口
  const url = apis[state.work];
  if (!url) {
    proxy.$message.error("未知的工作流程，无法上传文件");
    return;
  }

  // 3. 构造下载链接
  const baseUrl = "http://localhost:8082/api/excel/import/standard";
  const downloadUrl = `${baseUrl}?type=${type}`;

  // 4. 创建并触发下载
  const link = document.createElement("a");
  link.href = downloadUrl;
  link.setAttribute("download", ""); // 可留空，让后端决定文件名
  link.style.display = "none";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};


const submit = (values) => {
  let method = "post";
  const work = state.work;
  let url = apis[work];
  if (values.id) {
    method = "put";
    url = `${url}/${values.id}`;
  }
  proxy.$axios({ method, data: values, url }).then(({ success, msg }) => {
    if (success) {
      dialogRef.value.cancel();
      proxy.$message.success("提交成功");
      getList(1);
    }
  });
};

const action = (type, record) => {
  if (type === "add") {
    dialogRef.value.handleOpenForm({});
  } else if (type === "edit") {
    dialogRef.value.handleOpenForm({ ...record });
  } else if (type === "remove") {
    const url = apis[state.work];
    const apiUrl = `${url}/${record.id}`;
    proxy.$axios.delete(apiUrl).then(({ success }) => {
      if (success) {
        getList(1);
      }
    });
  }
};

let getList = () => {};
const handleClick = ({ key }) => {
  state.work = key;
  if (key === "-1") {
    state.innerColumns = null;
    state.innerFormConfig = null;

    state.formConfig = {
      title: "压缩空气电气转换",
      items: airToPowerFormItems,
    };

    const _columns = _.map(airToPowerColumns, (column) => ({
      ...column,
      width: 80,
      ellipsis: true,
    }));
    state.columns = [
      ..._columns,
      {
        title: "操作",
        key: "action",
        fixed: "right",
        width: 180,
        align: "center",
      },
    ];
  } else {
    const formItems = workFormItems[key];
    const one = _.find(formItems, { name: "shipId" });
    one.options = state.ships;

    state.formConfig = {
      title: showWorkLabel(key),
      items: formItems,
    };
    const _columns = _.map(workColumns[key], (column) => ({
      ...column,
      width: 100,
      ellipsis: true,
    }));
    state.columns = [
      ..._columns,
      {
        title: "操作",
        key: "action",
        fixed: "right",
        width: 180,
        align: "center",
      },
    ];

    let _innerColumns = null;
    if (innerColumns[key]) {
      _innerColumns = _.map(innerColumns[key], (column) => ({
        ...column,
        ellipsis: true,
      }));
      state.innerColumns = [
        ..._innerColumns,
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
        },
      ];
    } else {
      state.innerColumns = _innerColumns;
    }

    if (innerFormItems[key]) {
      state.innerFormConfig = {
        title: `${showWorkLabel(key)}子表单`,
        items: innerFormItems[key],
      };
    } else {
      state.innerFormConfig = null;
    }
  }

  const url = apis[key];
  getList = async (page) => {
    const { success, data } = await proxy.$axios.get(`${url}/list`, {
      params: { pageNumber: page, pageSize: state.pager.pageSize },
    });
    if (success) {
      const { content, totalElements } = data;
      computedFunc(key, content);
      state.data = content;
      state.pager.current = page;
      state.pager.total = totalElements;
    }
  };
  getList(1);
};

const computedFunc = (work, list) => {
  if (work === "0") {
    _.each(list, (o) => {
      const ratio = (o.cutLength * o.thickness) / 1000;
      o.power = (o.endPower - o.startPower) * 50;
      o.powerByUnit = o.power / ratio;
      o.o2 = o.endO2 - o.startO2;
      o.o2ByUnit = o.o2 / ratio;
      o.air = o.endAir - o.startAir;
      o.airByUnit = o.air / ratio;
    });
  } else if (work === "1") {
    _.each(list, (o) => {
      o.gas = o.endGas - o.startGas;
      o.gasByUnit = o.gas / o.length;
      o.o2 = o.endO2 - o.startO2;
      o.o2ByUnit = o.o2 / o.length;
    });
  } else if (work === "2") {
    _.each(list, (o) => {
      o.co2 = o.endCO2 - o.startCO2;
      o.co2ByUnit = o.co2 / o.length;
      let powers = 0;
      if (o.inner) {
        _.each(o.inner, (i) => {
          const r = i.endPower - i.startPower;
          powers += r;
        });
      }
      o.powers = powers;
      o.powerByUnit = powers / o.length;
    });
  } else if (["3-0", "3-1"].includes(work)) {
    _.each(list, (o) => {
      o.length = o.gapNum * Math.PI * o.d;
      o.powerByUnit = o.power / (o.length / 1000);
    });
  } else if (work === "4-0") {
    _.each(list, (o) => {
      o.air = o.endAir - o.startAir;
      o.airByUnit = o.air / o.area;
      const start = dayjs(o.startGas);
      const end = dayjs(o.endGas);
      o.gas = end.diff(start, "hours", true) * o.gasByHour;
      o.gasByUnit = o.gas / o.area;

      let powers = 0;
      if (o.inner) {
        _.each(o.inner, (i) => {
          const start = dayjs(i.startTime);
          const end = dayjs(i.endTime);
          i.totalPower = end.diff(start, "hours", true) * i.num * i.power;
          powers += i.totalPower;
        });
      }
      o.powers = powers;
      o.powersByUnit = powers / o.area;
    });
  } else if (work === "4-1") {
    _.each(list, (o) => {
      o.air = o.endAir - o.startAir;
      o.airByUnit = o.air / o.area;
    });
  } else if (work === "5-0") {
    _.each(list, (o) => {
      o.air = o.endAir - o.startAir;
      o.airByUnit = o.air / o.area;

      let powers = 0;
      if (o.inner) {
        _.each(o.inner, (i) => {
          if (i.startTime && i.endTime) {
            const start = dayjs(i.startTime);
            const end = dayjs(i.endTime);
            i.totalPower = end.diff(start, "hours", true) * i.num * i.power;
          } else {
            i.totalPower = 0;
          }
          powers += i.totalPower;
        });
      }
      o.power = powers;
      o.powerByUnit = powers / o.area;
    });
  } else if (work === "5-1") {
    _.each(list, (o) => {
      o.airByOne = o.endAir - o.startAir;
      o.air = o.num * o.airByOne;
      o.airByUnit = o.air / o.area;
    });
  } else if (["6-0", "6-1", "6-2"].includes(work)) {
    _.each(list, (o) => {
      let powers = 0;
      if (o.inner) {
        _.each(o.inner, (i) => {
          powers += i.powerByHour;
        });
      }
      o.power = powers;
      o.powerUnit = o.power / o.area;
    });
  } else if (work === "-1") {
    _.each(list, (o) => {
      o.inAir = o.outAir * o.timespan;
      o.powerByUnit = o.power / o.inAir;
    });
  }
};

const handleTableChange = ({ current }) => {
  getList(current);
};

onBeforeMount(async () => {
  const { success, data } = await proxy.$axios.get("/ship/dict");
  if (success) {
    state.ships = data;
  }

  handleClick({ key: state.work });
});

const innerAction = (type, record) => {
  if (type === "add") {
    dialogInnerRef.value.handleOpenForm(record);
  } else if (type === "edit") {
    dialogInnerRef.value.handleOpenForm({ ...record });
  } else if (type === "remove") {
    const url = apis[state.work];

    const apiUrl = `${url}/child/${record.id}`;
    proxy.$axios.delete(apiUrl).then(({ success }) => {
      if (success) {
        proxy.$message.success("删除成功");

        const all = [...state.data];
        const one = _.find(all, { id: record.pid });
        const _list = [...one.inner];
        one.inner = _.filter(_list, (o) => o.id !== record.id);

        computedFunc(state.work, all);
        state.data = all;
      }
    });
  }
};

const innerSubmit = (values) => {
  let method = "post";
  const work = state.work;
  let url = `${apis[work]}/child`;
  if (values.id) {
    method = "put";
    url = `${url}/${values.id}`;
  }
  proxy.$axios({ method, data: values, url }).then(({ success, data }) => {
    if (success) {
      dialogInnerRef.value.cancel();
      proxy.$message.success("提交成功");

      const all = [...state.data];
      const one = _.find(all, { id: values.pid });
      if (method === "put") {
        const i = _.findIndex(one.inner, { id: values.id });
        one.inner[i] = values;
      } else {
        one.inner = [...one.inner, data];
      }
      computedFunc(work, all);
      state.data = all;
    }
  });
};
</script>
<style lang="less" scoped>
.box {
  height: 100%;
  padding: 4px 0;
  background: #262626;
  display: flex;

  .left {
    width: 200px;
    height: 100%;
    display: flex;
    flex-direction: column;

    .menus {
      flex: 1;
      overflow-y: auto;
    }

    .extra {
      height: 40px;
      line-height: 40px;
      padding-left: 24px;
      background: #141414;
      vertical-align: middle;
      cursor: pointer;

      &:hover {
        color: #177ddc;
      }
    }

    .active {
      color: #177ddc;
      background-color: #111b26;
      border-right: 3px solid #177ddc;
    }
  }

  .right {
    width: calc(100% - 200px);
    padding: 10px;
    background-color: #000;
    height: 100%;
    overflow-y: auto;
  }
}
</style>
